<template>
  <div class="h-full flex flex-col bg-gray-50">
    <!-- 顶部标题栏 -->
    <div class="bg-white border-b border-gray-200 px-5 py-4 flex-shrink-0">
      <div class="flex items-center justify-between">
        <h2 class="m-0 text-gray-800 text-lg font-medium">调试历史</h2>
        <el-button
          v-if="history.length > 0"
          type="text"
          icon="el-icon-delete"
          size="small"
          class="!text-red-500 hover:!text-red-600"
          @click="handleClearAll"
        >
          清空历史
        </el-button>
      </div>
    </div>

    <!-- 历史记录列表 -->
    <div class="flex-1 overflow-y-auto p-5">
      <!-- 空状态 -->
      <div
        v-if="history.length === 0"
        class="flex flex-col items-center justify-center h-full text-gray-400"
      >
        <i class="el-icon-time text-6xl mb-3 opacity-50"></i>
        <p class="text-base m-0 mb-1">暂无调试历史</p>
        <p class="text-sm m-0 text-gray-400">开始调试程序后，历史记录将显示在这里</p>
      </div>

      <!-- 历史记录卡片列表 -->
      <div v-else class="max-w-5xl mx-auto space-y-4">
        <div
          v-for="(item, index) in history"
          :key="index"
          class="bg-white rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition-shadow"
        >
          <!-- 程序信息区域 -->
          <div class="p-4 border-b border-gray-100 cursor-pointer hover:bg-gray-50" @click="handleSelectProgram(item)">
            <div class="flex items-start justify-between">
              <div class="flex-1 overflow-hidden mr-4">
                <!-- 程序名称 -->
                <div class="flex items-center mb-2">
                  <i class="el-icon-document text-blue-500 text-lg mr-2"></i>
                  <h3 class="text-base font-medium text-gray-800 m-0 truncate">
                    {{ item.name }}
                  </h3>
                  <el-tag
                    v-if="item.breakpoints && item.breakpoints.length > 0"
                    size="mini"
                    type="success"
                    class="ml-3"
                  >
                    {{ item.breakpoints.length }} 个断点
                  </el-tag>
                </div>

                <!-- 完整路径 -->
                <div class="flex items-start mb-2">
                  <i class="el-icon-folder-opened text-gray-400 text-sm mr-2 mt-0.5"></i>
                  <p class="text-sm text-gray-600 m-0 break-all" :title="item.path">
                    {{ item.path }}
                  </p>
                </div>

                <!-- 最后使用时间 -->
                <div class="flex items-center">
                  <i class="el-icon-time text-gray-400 text-sm mr-2"></i>
                  <span class="text-xs text-gray-500">
                    最后调试：{{ formatTime(item.lastUsed) }}
                  </span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="flex flex-col gap-2">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-video-play"
                  @click.stop="handleDebug(item)"
                >
                  调试
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  class="!text-red-500 hover:!text-red-600"
                  @click.stop="handleRemove(index)"
                >
                  移除
                </el-button>
              </div>
            </div>
          </div>

          <!-- 断点列表区域 -->
          <div v-if="item.breakpoints && item.breakpoints.length > 0" class="p-4 bg-gray-50">
            <div class="flex items-center mb-3">
              <i class="el-icon-location-information text-orange-500 mr-2"></i>
              <h4 class="text-sm font-medium text-gray-700 m-0">断点列表</h4>
            </div>
            <div class="space-y-2">
              <div
                v-for="(bp, bpIndex) in item.breakpoints"
                :key="bpIndex"
                class="bg-white rounded border border-gray-200 p-3 hover:border-blue-300 transition-colors"
              >
                <div class="flex items-start justify-between">
                  <div class="flex-1 overflow-hidden">
                    <!-- 文件和行号 -->
                    <div class="flex items-center mb-1">
                      <el-tag size="mini" type="warning" class="mr-2">
                        行 {{ bp.line }}
                      </el-tag>
                      <span class="text-sm text-gray-700 truncate" :title="bp.file">
                        {{ formatFilePath(bp.file) }}
                      </span>
                    </div>

                    <!-- 条件断点信息 -->
                    <div v-if="bp.condition || bp.hitCondition" class="mt-2 space-y-1">
                      <div v-if="bp.condition" class="flex items-start text-xs">
                        <span class="text-gray-500 mr-2 flex-shrink-0">条件:</span>
                        <code class="text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded break-all">{{ bp.condition }}</code>
                      </div>
                      <div v-if="bp.hitCondition" class="flex items-start text-xs">
                        <span class="text-gray-500 mr-2 flex-shrink-0">命中次数:</span>
                        <code class="text-green-600 bg-green-50 px-1.5 py-0.5 rounded">{{ bp.hitCondition }}</code>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 无断点提示 -->
          <div v-else class="p-3 bg-gray-50 text-center">
            <span class="text-xs text-gray-400">暂无断点</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import debuggerApi from '../api/debugger'

export default {
  name: 'HistoryView',
  data() {
    return {
      history: []
    }
  },
  mounted() {
    this.loadHistory()
  },
  methods: {
    // 加载历史记录
    async loadHistory() {
      try {
        const result = await debuggerApi.loadHistory()
        if (result.success) {
          this.history = result.data || []
        } else {
          console.error('加载历史记录失败:', result.message)
          this.$message.error('加载历史记录失败')
        }
      } catch (error) {
        console.error('加载历史记录失败:', error)
        this.$message.error('加载历史记录失败')
      }
    },

    // 格式化时间
    formatTime(isoString) {
      if (!isoString) return ''
      const date = new Date(isoString)
      const now = new Date()
      const diff = now - date
      const seconds = Math.floor(diff / 1000)
      const minutes = Math.floor(seconds / 60)
      const hours = Math.floor(minutes / 60)
      const days = Math.floor(hours / 24)

      if (days > 0) {
        return `${days} 天前`
      } else if (hours > 0) {
        return `${hours} 小时前`
      } else if (minutes > 0) {
        return `${minutes} 分钟前`
      } else {
        return '刚刚'
      }
    },

    // 格式化文件路径（显示文件名和部分路径）
    formatFilePath(path) {
      if (!path) return ''
      const parts = path.split(/[/\\]/)
      if (parts.length > 3) {
        return '.../' + parts.slice(-3).join('/')
      }
      return parts.join('/')
    },

    // 选择程序（点击卡片）
    handleSelectProgram(item) {
      // 触发事件通知父组件切换到调试器视图并加载程序（包含断点）
      this.$emit('select-program', {
        path: item.path,
        breakpoints: item.breakpoints || []
      })
    },

    // 开始调试
    handleDebug(item) {
      // 触发事件通知父组件切换到调试器视图并启动调试（包含断点）
      this.$emit('debug-program', {
        path: item.path,
        breakpoints: item.breakpoints || []
      })
    },

    // 移除单个历史记录
    handleRemove(index) {
      this.$confirm('确定要移除这条历史记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.history.splice(index, 1)
        await this.saveHistory()
        this.$message.success('已移除')
      }).catch(() => {})
    },

    // 清空所有历史记录
    handleClearAll() {
      this.$confirm('确定要清空所有历史记录吗？此操作不可恢复。', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.history = []
        await this.saveHistory()
        this.$message.success('已清空历史记录')
      }).catch(() => {})
    },

    // 保存历史记录
    async saveHistory() {
      try {
        const result = await debuggerApi.saveHistory(this.history)
        if (!result.success) {
          console.error('保存历史记录失败:', result.message)
          this.$message.error('保存历史记录失败')
        }
      } catch (error) {
        console.error('保存历史记录失败:', error)
        this.$message.error('保存历史记录失败')
      }
    }
  }
}
</script>

<style scoped>
/* 使用 Tailwind CSS，无需额外样式 */
</style>
